package cn.laixueit.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileUpload {

    @PostMapping("/img")
    public String uploadImg(@RequestParam("img") MultipartFile file, HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        ServletContext context = session.getServletContext();
        String realPath = context.getRealPath("/img/da/b/c");
//        System.out.println(realPath);
        // 逻辑完善D:\codeWork\java1101\springmvc_05\target\springmvc_05-1.0-SNAPSHOT\
        File f = new File(realPath);
        if(!f.exists()){
           f.mkdirs();
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = file.getOriginalFilename();
        filename = uuid + "_"+filename;
        File newfile = new File(f,filename);
        file.transferTo(newfile);
        return newfile.getAbsolutePath();
    }
}
